package com.coffee.web.controller;

import cn.hutool.core.codec.Base64;
import com.alibaba.fastjson.JSONObject;
import com.coffee.admin.api.common.query.GtRegionQuery;
import com.coffee.admin.api.common.result.GtRegionResult;
import com.coffee.admin.api.common.service.GtRegionService;
import com.coffee.admin.api.common.service.RedisService;
import com.coffee.admin.api.merchant.query.MerchantCityQuery;
import com.coffee.admin.api.merchant.query.MerchantIntegralLogQuery;
import com.coffee.admin.api.merchant.req.MerchantCityReq;
import com.coffee.admin.api.merchant.req.MerchantUpdateMobileReq;
import com.coffee.admin.api.merchant.req.RegisterReq;
import com.coffee.admin.api.merchant.result.*;
import com.coffee.admin.api.merchant.service.ConfigureService;
import com.coffee.admin.api.merchant.service.MerchantCityService;
import com.coffee.admin.api.merchant.service.MerchantIntegralLogService;
import com.coffee.admin.api.merchant.service.MerchantService;
import com.coffee.admin.api.platform.result.RechargeRuleResult;
import com.coffee.admin.api.platform.service.RechargeRuleService;
import com.coffee.core.anotation.LoginCheck;
import com.coffee.core.anotation.LoginStatus;
import com.coffee.core.anotation.OperLog;
import com.coffee.core.entity.LoginUser;
import com.coffee.core.entity.Page;
import com.coffee.core.entity.PagerInfo;
import com.coffee.core.enums.DailiMerchantRoleEnum;
import com.coffee.core.enums.ExceptionEnum;
import com.coffee.core.enums.MerchantCityTypeEnum;
import com.coffee.core.exception.BusinessException;
import com.coffee.core.exception.ValidateBusinessException;
import com.coffee.core.result.Result;
import com.coffee.core.util.*;
import com.coffee.daili.api.query.DailiMerchantQuery;
import com.coffee.daili.api.service.DailiMerchantService;
import com.coffee.order.api.inquire.req.MerchantIntegralLogReq;
import com.coffee.order.api.sku.service.CommonPayService;
import com.coffee.web.utils.WeixinGzhAppletsUtil;
import net.logstash.logback.encoder.org.apache.commons.lang.StringUtils;
import org.apache.dubbo.config.annotation.DubboReference;
import org.bouncycastle.jce.provider.BouncyCastleProvider;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;

import java.io.*;
import java.net.HttpURLConnection;

import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.net.URL;
import java.net.URLDecoder;
import java.security.*;
import java.security.spec.InvalidParameterSpecException;
import java.util.*;

@RestController
@RequestMapping("/merchant")
public class MerchantController extends BaseController {
    private static final Logger LOG = LoggerFactory.getLogger(MerchantController.class);

    @DubboReference
    private MerchantService merchantService;
    @DubboReference
    private MerchantIntegralLogService merchantIntegralLogService;
    @DubboReference
    private MerchantCityService merchantCityService;
    @DubboReference
    private CommonPayService commonPayService;
    @DubboReference
    private GtRegionService gtRegionService;
    @DubboReference
    private ConfigureService configureService;
    @DubboReference
    private DailiMerchantService dailiMerchantService;
    @DubboReference
    private RedisService redisService;
    @DubboReference
    private RechargeRuleService rechargeRuleService;

    @Value("${parameter.customer.mobile}")
    public String mobile;
    @Value("${parameter.customer.url}")
    public String url;
    @Value("${parameter.customer.time}")
    public String time;
    @Value("${parameter.webDomain}")
    public String webDomain;
    @Value("${parameter.weixin.appId}")
    public String appId;
    @Value("${parameter.weixin.appSecret}")
    public String appSecret;
    @Value("${parameter.weixin.newAppId}")
    public String newAppId;
    @Value("${parameter.weixin.newAppSecret}")
    public String newAppSecret;
    @Value("${parameter.weixin.gzhAppId}")
    public String gzhAppId;
    @Value("${parameter.weixin.gzhAppSecret}")
    public String gzhAppSecret;
    @Value("${TAG}")
    private String environment;


    @OperLog(operModul = "商户-商户详情", operDesc = "商户详情")
    @RequestMapping(value = "/detail", method = {RequestMethod.POST})
    public Result<MerchantResult> findList(HttpServletRequest request) {
        LoginUser merchant = getMerchant();
        Result<MerchantResult> result = Result.success(null);
        if (merchant==null){
            return result;
        }
        MerchantResult merchantResult = merchantService.getDetail(merchant.getUserId());
        result.setData(merchantResult);
        return result;
    }


    @OperLog(operModul = "商户-根据手机号查询商户", operDesc = "根据手机号查询商户")
    @LoginCheck
    @RequestMapping(value = "/get/byMobile", method = {RequestMethod.POST})
    public Result<MerchantResult> getByMobile(HttpServletRequest request, @RequestBody JSONObject jsonObject) {
        LoginUser merchant = getMerchant();
        Result<MerchantResult> result = Result.success(null);
        String mobile = jsonObject.getString("mobile");
        MerchantResult merchantResult = null;
        try {
            merchantResult = merchantService.getDetailByMobile(mobile);
            MerchantResult dailiMerchant = merchantService.getDetail(merchant.getUserId());
            dailiMerchantService.dailiMerchantIsHaving(mobile, dailiMerchant.getMobile());
        } catch (BusinessException e) {
            result.setCode(e.getCode());
            result.setMsg(e.getMessage());
            return result;
        }
        result.setData(merchantResult);
        return result;
    }


    @RequestMapping(value = "/all/address", method = {RequestMethod.POST})
    public Result<List<GtRegionResult>> address(HttpServletRequest request, @RequestBody JSONObject jsonObject) {
        String isMustCity = jsonObject.getString("isMustCity");
        Result<List<GtRegionResult>> result = Result.success(null);
        if ("Y".equals(isMustCity)) {
            GtRegionQuery param = new GtRegionQuery();
            param.setIsMustCity(isMustCity);
            param.setIsDisable("N");
            List<GtRegionResult> list = gtRegionService.getList(param);
            result.setData(list);
        } else {
            List<GtRegionResult> list = gtRegionService.getList();
            result.setData(list);
        }
        return result;
    }

    @OperLog(operModul = "商户-收获地址列表", operDesc = "收获地址列表列表")
    @LoginCheck
    @RequestMapping(value = "/address/list", method = {RequestMethod.POST})
    public Result<List<MerchantCityResult>> addressList(HttpServletRequest request) {
        LoginUser merchant = getMerchant();
        Result<List<MerchantCityResult>> result = Result.success(null);
        MerchantCityQuery param = new MerchantCityQuery();
        param.setMerchantId(merchant.getUserId());
        param.setType(MerchantCityTypeEnum.USER.getCode());
        List<MerchantCityResult> merchantCityServiceList = merchantCityService.getList(param);
        result.setData(merchantCityServiceList);
        return result;
    }

    @OperLog(operModul = "商户-新增或修改地址", operDesc = "收获地址列表列表")
    @LoginCheck
    @RequestMapping(value = "/address/addOrUpdate", method = {RequestMethod.POST})
    public Result<String> addressList(@RequestBody MerchantCityReq req, HttpServletRequest request) {
        LoginUser merchant = getMerchant();
        Result<String> result = Result.success(null);
        req.setMerchantId(merchant.getUserId());
        try {
            req.setType(MerchantCityTypeEnum.USER.getCode());
            merchantCityService.addOrUpdate(req);
        } catch (BusinessException e) {
            return Result.failed(e.getCode(), e.getMessage());
        }
        result.setData("SUCCESS");
        return result;
    }


    @OperLog(operModul = "商户-删除地址", operDesc = "删除地址")
    @LoginCheck
    @RequestMapping(value = "/address/delete", method = {RequestMethod.POST})
    public Result<String> addressDelete(@RequestBody JSONObject jsonObject, HttpServletRequest request) {
        LoginUser merchant = getMerchant();
        Result<String> result = Result.success(null);
        Integer id = jsonObject.getInteger("id");
        merchantCityService.delete(id, merchant.getUserId(), MerchantCityTypeEnum.USER.getCode());
        result.setData("SUCCESS");
        return result;
    }

    @OperLog(operModul = "商户-设为默认", operDesc = "设为默认")
    @LoginCheck
    @RequestMapping(value = "/address/isDefault", method = {RequestMethod.POST})
    public Result<String> addressUpdateIsDefault(@RequestBody JSONObject jsonObject, HttpServletRequest request) {
        LoginUser merchant = getMerchant();
        Result<String> result = Result.success(null);
        try {
            Integer id = jsonObject.getInteger("id");
            String isDefault = jsonObject.getString("isDefault");
            merchantCityService.updateIsDefault(id, merchant.getUserId(), isDefault);
        } catch (BusinessException e) {
            return Result.failed(e.getCode(), e.getMessage());
        }
        result.setData("SUCCESS");
        return result;
    }


    @OperLog(operModul = "商户-更改头像", operDesc = "更改头像")
    @LoginCheck
    @RequestMapping(value = "/headPortrait/update", method = {RequestMethod.POST})
    public Result<String> headImageUpdate(@RequestBody JSONObject jsonObject, HttpServletRequest request) {
        LoginUser merchant = getMerchant();
        String headPortrait = jsonObject.getString("headPortrait");
        String nickname = jsonObject.getString("nickname");
        Result<String> result = Result.success(null);
        MerchantResult merchantResult = new MerchantResult();
        merchantResult.setId(merchant.getUserId());
        merchantResult.setHeadPortrait(headPortrait);
        merchantResult.setNickname(nickname);
        try {
            merchantService.update(merchantResult);
        } catch (BusinessException e) {
            return Result.failed(e.getCode(), e.getMessage());
        }
        result.setData("SUCCESS");
        return result;
    }

    @OperLog(operModul = "商户-更改手机号", operDesc = "更改手机号")
    @LoginCheck
    @PostMapping(value = "/updateMobile")
    public Result<String> merchantUpdateMobile(@RequestBody MerchantUpdateMobileReq req, HttpServletRequest request, HttpServletResponse response) {
        try {
            Integer userId = getMerchant().getUserId();
            req.setId(userId);
            merchantService.updateMobile(req);
            return Result.success("SUCCESS");
        } catch (BusinessException e) {
            return Result.failed(e.getCode(), e.getMessage());
        }
    }


    @OperLog(operModul = "商户-获取openId", operDesc = "获取openId")
    @PostMapping(value = "/getOpenId")
    public Result<String> merchantUpdateMobile(@RequestBody JSONObject jsonObject, HttpServletRequest request, HttpServletResponse response) {
        String code = jsonObject.getString("code");
        Integer appletType = jsonObject.getInteger("appletType");
        String encryptedData = jsonObject.getString("encryptedData");
        String iv = jsonObject.getString("iv");
        if (StringUtils.isBlank(code)) {
            return Result.failed(9999, "code不能为空");
        }
        Map<String, String> params = new HashMap<>();
        if (appletType == 1) {
            params.put("appid", appId);
            params.put("secret", appSecret);
        } else {
            params.put("appid", newAppId);
            params.put("secret", newAppSecret);
        }
        params.put("js_code", code);
        params.put("grant_type", "authorization_code");
        String str = HttpClientUtil.doPost("https://api.weixin.qq.com/sns/jscode2session", params);
        LOG.info("getOpenId===" + JSONObject.toJSONString(str));
        //解析相应内容（转换成json对象）
        JSONObject json = JSONObject.parseObject(str);
        if (StringUtil.isEmpty(json.getString("errcode"))) {
            //获取会话密钥（session_key）
            String sessionKey = json.get("session_key").toString();
            //用户的唯一标识（openid）
            String openid = (String) json.get("openid");
            if (org.apache.commons.lang.StringUtils.isBlank(iv) || org.apache.commons.lang.StringUtils.isBlank(encryptedData)) {
                // 这俩参数值为空，说明，已授权不用再次重复授权，此时，上面接口获取openid就是对的。直接返回
                return Result.success(openid);
            }
            // 参数不为空，则为第一次授权，需要解密获取。
            JSONObject jsonObject2 = getUserInfo(encryptedData, sessionKey, iv);
            Map<String, String> res = new HashMap<>();
            LOG.info("解密结果：" + jsonObject2.toString());
            return Result.success(jsonObject2.getString("openId"));
        } else {
            return Result.failed(ExceptionEnum.ERROR_9998.getCode(), json.getString("errmsg"));
        }
    }


    @OperLog(operModul = "商户-获取gzhopenId", operDesc = "获取gzhopenId")
    @PostMapping(value = "/getGzhOpenId")
    public Result<String> merchantUpdateGzh(@RequestBody JSONObject jsonObject, HttpServletRequest request, HttpServletResponse response) throws BusinessException {
        String code = jsonObject.getString("code");
        String token = jsonObject.getString("token");
        if (StringUtils.isBlank(code)) {
            return Result.failed(9999, "code不能为空");
        }
        String loginUserStr = (String) redisService.get(token);
        LoginUser loginUser = JSONObject.parseObject(loginUserStr, LoginUser.class);
        if (loginUser == null) {
            return Result.success("token不存在");
        }
        Map<String, String> params = new HashMap<>();
        params.put("appid", gzhAppId);
        params.put("secret", gzhAppSecret);
        params.put("code", code);
        params.put("grant_type", "authorization_code");
        String str = HttpClientUtil.get("https://api.weixin.qq.com/sns/oauth2/access_token", params);
        LOG.info("getOpenId===" + JSONObject.toJSONString(str));
        String openId = JSONObject.parseObject(str).getString("openid");
        MerchantResult merchantResult = new MerchantResult();
        merchantResult.setId(loginUser.getUserId());
        merchantResult.setGzhOpenId(openId);
        merchantService.update(merchantResult);
        return Result.success(openId);

    }

    @OperLog(operModul = "商户-微信登录", operDesc = "微信登录")
    @PostMapping(value = "/weixin/login")
    public Result<String> weixinLogin(@RequestBody JSONObject jsonObject, HttpServletRequest request, HttpServletResponse response) {
        String code = jsonObject.getString("code");
        Integer appletType = jsonObject.getInteger("appletType");
        String encryptedData = jsonObject.getString("encryptedData");
        String iv = jsonObject.getString("iv");
        String nickname = jsonObject.getString("nickname");
        String headPortrait = jsonObject.getString("headPortrait");
        Integer dailiMerchantId = jsonObject.getInteger("dailiMerchantId");
        String role = jsonObject.getString("role");
        if (StringUtils.isBlank(code)) {
            return Result.failed(9999, "code不能为空");
        }
        if (StringUtils.isBlank(encryptedData)) {
            return Result.failed(9999, "encryptedData不能为空");
        }
        if (StringUtils.isBlank(iv)) {
            return Result.failed(9999, "iv不能为空");
        }
        Map<String, String> params = new HashMap<>();
        if (appletType == 1) {
            params.put("appid", appId);
            params.put("secret", appSecret);
        } else {
            params.put("appid", newAppId);
            params.put("secret", newAppSecret);
        }
        params.put("js_code", code);
        params.put("grant_type", "authorization_code");
        String str = HttpClientUtil.doPost("https://api.weixin.qq.com/sns/jscode2session", params);
        //解析相应内容（转换成json对象）
        JSONObject json = JSONObject.parseObject(str);
        LOG.info("json===" + json);
        if (StringUtil.isEmpty(json.getString("errcode"))) {
            //获取会话密钥（session_key）
            String sessionKey = json.get("session_key").toString();
            //用户的唯一标识（openid）
            String openid = (String) json.get("openid");
            // 参数不为空，则为第一次授权，需要解密获取。
            JSONObject jsonObject2 = getUserInfo(encryptedData, sessionKey, iv);
            LOG.info("解密结果：" + jsonObject2);
            String phoneNumber = jsonObject2.getString("phoneNumber");
            RegisterReq req = new RegisterReq();
            req.setMobile(phoneNumber);
            req.setOpenId(openid);
            req.setHeadPortrait(headPortrait);
            req.setNickname(nickname);
            req.setDailiMerchantId(dailiMerchantId);
            req.setRole(role);
            ToolMobileSegmentResult mobileSeg = ZhongtailClient.getMobileSeg(req.getMobile());
            req.setCity(mobileSeg.getCity());
            req.setProvince(mobileSeg.getProvince());
            try {
                String s = merchantService.weixingRegister(req);
                return Result.success(s);
            } catch (BusinessException e) {
                Result.failed(e.getCode(), e.getMessage());
            }
        } else {
            return Result.failed(ExceptionEnum.ERROR_9998.getCode(), json.getString("errmsg"));
        }
        return null;
    }


    public JSONObject getUserInfo(String encryptedData, String sessionKey, String iv) {
        // 被加密的数据
        byte[] dataByte = Base64.decode(encryptedData);
        // 加密秘钥
        byte[] keyByte = Base64.decode(sessionKey);
        // 偏移量
        byte[] ivByte = Base64.decode(iv);
        try {
            // 如果密钥不足16位，那么就补足.  这个if 中的内容很重要
            int base = 16;
            if (keyByte.length % base != 0) {
                int groups = keyByte.length / base + (keyByte.length % base != 0 ? 1 : 0);
                byte[] temp = new byte[groups * base];
                Arrays.fill(temp, (byte) 0);
                System.arraycopy(keyByte, 0, temp, 0, keyByte.length);
                keyByte = temp;
            }
            // 初始化
            Security.addProvider(new BouncyCastleProvider());
            Cipher cipher = Cipher.getInstance("AES/CBC/PKCS7Padding", "BC");
            SecretKeySpec spec = new SecretKeySpec(keyByte, "AES");
            AlgorithmParameters parameters = AlgorithmParameters.getInstance("AES");
            parameters.init(new IvParameterSpec(ivByte));
            cipher.init(Cipher.DECRYPT_MODE, spec, parameters);// 初始化
            byte[] resultByte = cipher.doFinal(dataByte);
            if (null != resultByte && resultByte.length > 0) {
                String result = new String(resultByte, "UTF-8");
                LOG.info("result===" + result);
                return JSONObject.parseObject(result);
            }
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        } catch (NoSuchPaddingException e) {
            e.printStackTrace();
        } catch (InvalidParameterSpecException e) {
            e.printStackTrace();
        } catch (IllegalBlockSizeException e) {
            e.printStackTrace();
        } catch (BadPaddingException e) {
            e.printStackTrace();
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (InvalidKeyException e) {
            e.printStackTrace();
        } catch (InvalidAlgorithmParameterException e) {
            e.printStackTrace();
        } catch (NoSuchProviderException e) {
            e.printStackTrace();
        }
        return null;
    }


    @OperLog(operModul = "商户-咖啡店列表", operDesc = "收获地址列表列表")
    @LoginCheck
    @RequestMapping(value = "/shop/list", method = {RequestMethod.POST})
    public Result<List<MerchantShopResult>> shopList(HttpServletRequest request) {
        LoginUser merchant = getMerchant();
        Result<List<MerchantShopResult>> result = Result.success(null);
        MerchantCityQuery param = new MerchantCityQuery();
        param.setMerchantId(merchant.getUserId());
        param.setType(MerchantCityTypeEnum.SHOP.getCode());
        List<MerchantShopResult> shopList = merchantCityService.getShopList(param);
        result.setData(shopList);
        return result;
    }

    @OperLog(operModul = "商户-新增或修改地址", operDesc = "收获地址列表列表")
    @LoginCheck
    @RequestMapping(value = "/shop/addOrUpdate", method = {RequestMethod.POST})
    public Result<String> shopAdd(@RequestBody MerchantCityReq req, HttpServletRequest request) {
        LoginUser merchant = getMerchant();
        Result<String> result = Result.success(null);
        req.setMerchantId(merchant.getUserId());
        try {
            req.setType(MerchantCityTypeEnum.SHOP.getCode());
            merchantCityService.addOrUpdate(req);
        } catch (BusinessException e) {
            return Result.failed(e.getCode(), e.getMessage());
        }
        result.setData("SUCCESS");
        return result;
    }


    @OperLog(operModul = "商户-删除地址", operDesc = "删除地址")
    @LoginCheck
    @RequestMapping(value = "/shop/delete", method = {RequestMethod.POST})
    public Result<String> shopDelete(@RequestBody JSONObject jsonObject, HttpServletRequest request) {
        LoginUser merchant = getMerchant();
        Result<String> result = Result.success(null);
        Integer id = jsonObject.getInteger("id");
        merchantCityService.delete(id, merchant.getUserId(), MerchantCityTypeEnum.SHOP.getCode());
        result.setData("SUCCESS");
        return result;
    }


    @OperLog(operModul = "商户-联系客服", operDesc = "联系客服")
    @LoginCheck
    @RequestMapping(value = "/customer/service", method = {RequestMethod.POST})
    public Result<Map<String, String>> customerService(HttpServletRequest request) {
        LoginUser merchant = getMerchant();
        Result<Map<String, String>> result = Result.success(null);
        Map<String, String> map = new HashMap<>();
        map.put("mobile", mobile);
        map.put("url", url);
        map.put("time", time);
        result.setData(map);
        return result;
    }

    @OperLog(operModul = "商户-商户积分详情", operDesc = "商户积分详情")
    @LoginCheck
    @RequestMapping(value = "/integral", method = {RequestMethod.POST})
    public Result<IntegralResult> integral(HttpServletRequest request) {
        LoginUser merchant = getMerchant();
        Result<IntegralResult> result = Result.success(null);
        IntegralResult integralResult = merchantService.getIntegralResult(merchant.getUserId());
        result.setData(integralResult);
        return result;
    }

    @OperLog(operModul = "商户-积分流水", operDesc = "积分流水")
    @LoginCheck
    @RequestMapping(value = "/integral/log/list", method = {RequestMethod.POST})
    public Result<Page<MerchantIntegralLogResult>> merchantIntegralLog(@RequestBody MerchantIntegralLogReq req, HttpServletRequest request) {
        Result<Page<MerchantIntegralLogResult>> result = Result.success(null);
        MerchantIntegralLogQuery param = new MerchantIntegralLogQuery();
        BeanUtils.copyProperties(param, req);
        PagerInfo pagerInfo = setDefaultPageInfo(req.getPageSize(), req.getPageIndex());
        param.setMerchantId(getMerchant().getUserId());
        Page<MerchantIntegralLogResult> pager = merchantIntegralLogService.getPager(param, pagerInfo);
        result.setData(pager);
        return result;
    }

    @OperLog(operModul = "商户-整合接口", operDesc = "整合接口")
    @RequestMapping(value = "/configure/list", method = {RequestMethod.POST})
    public Result<Map<String, List<ConfigureResult>>> merchantIntegralLog(HttpServletRequest request) {
        Result<Map<String, List<ConfigureResult>>> result = Result.success(null);
        Map<String, List<ConfigureResult>> itemMapList = configureService.getItemMapList();
        result.setData(itemMapList);
        return result;
    }

    @LoginCheck
    @RequestMapping("/front/create/qrcode")
    public Result<String> callback(HttpServletRequest request, HttpServletResponse response, @RequestBody JSONObject json) {
        Map<String, String> map = new HashMap<>();
        HttpURLConnection httpURLConnection = null;
        try {
            String role = json.getString("role");
            MerchantResult detail = merchantService.getDetail(getMerchant().getUserId());
            if (DailiMerchantRoleEnum.PARTNER.getCode().equals(detail.getDailiRole()) && "fenxiao".equals(role)) {
                DailiMerchantQuery param = new DailiMerchantQuery();
                param.setRole(DailiMerchantRoleEnum.DISTRIBUTOR.getCode());
                param.setPid(detail.getDailiMerchantId());
                param.setIsEnable("Y");
                Integer count = dailiMerchantService.count(param);
                if (count >= detail.getPeopleNumber()) {
                    return Result.failed(ExceptionEnum.ERROR_1905.getCode(), ExceptionEnum.ERROR_1905.getMessage());
                }
            }
            String cover = getCover(httpURLConnection, detail.getDailiMerchantId(), role);
            return Result.success(cover);
        } catch (BusinessException e) {
            e.printStackTrace();
            return Result.failed(e.getCode(), e.getMessage());
        } catch (Exception e) {
            e.printStackTrace();
            return Result.failed(ExceptionEnum.ERROR_9999.getCode(), e.getMessage());
        } finally {
            if (httpURLConnection != null) {
                httpURLConnection.disconnect();
            }
        }
    }

    public String getCover(HttpURLConnection httpURLConnection, Integer dailiMerchantId, String role) throws Exception {
        Object accessToken = redisService.get("xcxAccessToken");
        String accessTokenStr = null;
        if (accessToken == null) {
            JSONObject accessToken1 = WeixinGzhAppletsUtil.getAccessToken();
            accessToken1.put("expires_time", DateUtil.addSeconds(new Date(), accessToken1.getInteger("expires_in")));
            redisService.set("xcxAccessToken", accessToken1);
            accessTokenStr = accessToken1.getString("access_token");
        } else {
            JSONObject jsonObject = JSONObject.parseObject(JSONObject.toJSONString(accessToken));
            if (jsonObject.getDate("expires_time").before(new Date())) {
                JSONObject accessToken2 = WeixinGzhAppletsUtil.getAccessToken();
                accessToken2.put("expires_time", DateUtil.addSeconds(new Date(), accessToken2.getInteger("expires_in")));
                redisService.set("xcxAccessToken", accessToken2);
                accessTokenStr = accessToken2.getString("access_token");
            } else {
                accessTokenStr = jsonObject.getString("access_token");
            }
        }
        //小程序统一消息推送

        URL url = new URL("https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token=" + accessTokenStr);
        httpURLConnection = (HttpURLConnection) url.openConnection();
        httpURLConnection.setRequestMethod("POST");// 提交模式
        // 发送POST请求必须设置如下两行
        httpURLConnection.setDoOutput(true);
        httpURLConnection.setDoInput(true);
        // 获取URLConnection对象对应的输出流
        PrintWriter printWriter = new PrintWriter(httpURLConnection.getOutputStream());
        // 发送请求参数
        JSONObject paramJson = new JSONObject();
        paramJson.put("scene", "dMI=" + dailiMerchantId + "&role=" + role);
        paramJson.put("page", "pages/vx-login/index");
        if (environment.equals("stg")) {
            paramJson.put("env_version", "trial");
        }
        LOG.info("paramJson===" + paramJson + ",token==" + accessTokenStr);
        printWriter.write(paramJson.toString());
        // flush输出流的缓冲
        printWriter.flush();
        BufferedInputStream bis = new BufferedInputStream(httpURLConnection.getInputStream());
        try (InputStream is = httpURLConnection.getInputStream(); ByteArrayOutputStream baos = new ByteArrayOutputStream();) {
            byte[] buffer = new byte[1024];
            int len = -1;
            while ((len = is.read(buffer)) != -1) {
                baos.write(buffer, 0, len);
            }
            String s = new String(baos.toByteArray());
            if (s.length() < 300) {
                JSONObject jsonObject = JSONObject.parseObject(s);
                Integer errcode = jsonObject.getInteger("errcode");
                if (errcode == 40001) {
                    JSONObject accessToken1 = WeixinGzhAppletsUtil.getAccessToken();
                    accessToken1.put("expires_time", DateUtil.addSeconds(new Date(), accessToken1.getInteger("expires_in")));
                    redisService.set("xcxAccessToken", accessToken1);
                    HttpURLConnection httpURLConnection1 = null;
                    return getCover(httpURLConnection1, dailiMerchantId, role);
                } else {
                    throw new BusinessException(errcode, jsonObject.getString("errmsg"));
                }

            }
            return ("data:image/png;base64," + Base64.encode(baos.toByteArray()));
        }
    }

    @OperLog(operModul = "余额充值规则记录", operDesc = "余额充值规则记录")
    @RequestMapping(value = "/rechargeRule/list", method = {RequestMethod.POST})
    public Result<Page<RechargeRuleResult>> rechargeRuleList(@RequestBody MerchantIntegralLogReq req, HttpServletRequest request) {
        Result<Page<RechargeRuleResult>> result = Result.success(null);
        PagerInfo pagerInfo = setDefaultPageInfo(req.getPageSize(), req.getPageIndex());
        Page<RechargeRuleResult> rechargeRuleResultPage = rechargeRuleService.listAllRules(pagerInfo);
        result.setData(rechargeRuleResultPage);
        return result;
    }

    public static void main(String[] args) {
        System.out.println("dailiMerchantId=269&role=merchant".length());
    }

}

